<template>
	<view :style="{width:'100%',height:'100%',position: 'relative'}">
		<view v-if="ready" :style="{left:'20px', right:'20px',top:'20px',position: 'absolute'}">
			<button type="primary" :style="{marginBottom:'15px'}" @click="anchorStartLive">主播开播</button>
			
			相亲房间列表<br>
			<button v-for="(item,index) in liveRoomList"
			        :key="index"
			        type="primary"
			        :style="{marginBottom:'15px'}"
			        @click.native="audienceEnterRoom(item)">{{`${item.liveuser_info.user_nickname}(${item.uid})`}}
			</button>
		</view>
		<view v-else :style="{left:'0px', right:'0px',top:'0px',bottom:'0px',overflow:'hidden',position: 'absolute'}">
			
			<div ref="anchorView"
			     :style="{width:'100%',height:'100%',position: 'absolute'}">
			</div>
			<div ref="audienceView"
			     :style="{width:'140px',right:'0px',top:'0px',bottom:'0px', overflow:'scroll',position: 'absolute'}">
			</div>
			<view v-show="showUpMic" :style="{width:'80px',left:'15px',bottom:'15px',position: 'absolute'}">
				<button type="primary" @click="audienceMic">{{upMic?"下麦":"上麦"}}</button>
			</view>
		
		</view>
	
	
	</view>
</template>

<script>
    import AgoraRTC from '../../static/js/agorasdk/AgoraRTC_N-4.13.0'
    import appConfig from '../../utils/js/app-config'
    import Toast from "../../components/common/toast";
    import Http from "../../utils/http";

    export default {
        name: "agorasdk",
        data() {
            const self = uni.getStorageSync('user')//自己
            return {
                liveRoomList: [],//相亲房间列表
                uid: self.id,//自己的id
                token: self.token,//自己的token
                ready: true,
                anchorInfo: {//主播的推流信息
                    uid: '',
                    audioTrack: null,
                    videoTrack: null
                },
                audienceInfo: [],//上麦观众的推流信息
                upMic: false,//观众自己是否上麦
            }
        },
        computed: {
            showUpMic() {
                return this.anchorInfo.uid !== '' && this.anchorInfo.uid !== this.uid
            }
        },

        methods: {
            /**
             * 获取相亲间列表
             */
            getXqRoomList() {
                const that = this
                Http.request(Http.getXqRoomList, {
                    'uid': that.uid,
                    'token': that.token,
                    'p': '1'
                }, {
                    onSucc(code, msg, info) {
                        that.liveRoomList = info
                    }
                })
            },


            /**
             * 观众上麦和下麦
             */
            audienceMic() {
                if (this.upMic) {//下麦
                    this.rtcClient.unpublish().then(res => {
                        this.upMic = false
                        this.rtcClient.setClientRole("audience")//用户角色设为观众
                        //自己是否在推流
                        let index = this.audienceInfo.findIndex(value => value.uid === this.uid)
                        if (index >= 0) {
                            let selfMicInfo = this.audienceInfo[index]
                            if (selfMicInfo.audioTrack) {
                                console.log("Agora:", "自己关闭音频轨道")
                                selfMicInfo.audioTrack.close()
                            }
                            if (selfMicInfo.videoTrack) {
                                console.log("Agora:", "自己关闭视频轨道")
                                selfMicInfo.videoTrack.close()
                            }
                            this.audienceInfo.splice(index, 1)

                            const localPlayerContainer = document.getElementById(this.uid);
                            localPlayerContainer.remove();
                        }
                    })
                } else {//上麦
                    this.startPush(audioAndVideoTrack => {
                        this.upMic = true
                        this.audienceInfo.push({
                            uid: this.uid,
                            audioTrack: audioAndVideoTrack[0],
                            videoTrack: audioAndVideoTrack[1]
                        })
                        console.log('$refs:', this.$refs)
                        const localPlayerContainer = document.createElement("div");
                        localPlayerContainer.id = this.uid;
                        localPlayerContainer.style.width = '140px'
                        localPlayerContainer.style.height = '200px'
                        localPlayerContainer.style.border = '#000 1px solid'
                        localPlayerContainer.style.backgroundColor = '#ccc'
                        localPlayerContainer.style.boxSizing = 'border-box'
                        this.$refs.audienceView.append(localPlayerContainer);
                        audioAndVideoTrack[1].play(localPlayerContainer)

                    })
                }
            },

            /**
             * 观众进入房间
             */
            audienceEnterRoom(item) {
                this.anchorInfo.uid = item.uid
                this.initAndJoin(() => {
                    Toast.show("成功进入房间")
                    this.ready = false
                })
            },

            /**
             * 主播开播
             */
            anchorStartLive() {
                this.anchorInfo.uid = this.uid
                Http.request(Http.checkHongNiang, {
                    'uid': this.uid,
                    'token': this.token,
                }, (code, msg, info) => {
                    if (code === 0) {
                        this.rtcToken = info[0].live_token
                        this.initAndJoin(() => {
                            this.ready = false
                            this.startPush(audioAndVideoTrack => {
                                this.anchorInfo.audioTrack = audioAndVideoTrack[0]
                                this.anchorInfo.videoTrack = audioAndVideoTrack[1]
                                audioAndVideoTrack[1].play(this.$refs.anchorView)

                                Http.request(Http.createXqRoom, {
                                    'uid': this.uid,
                                    'token': this.token,
                                    'title': '',
                                    'thumb': '',
                                    'city': '泰安市',
                                    'province': '山东省',
                                    'lat': '36.178052',
                                    'lng': '117.086263',
                                    'deviceinfo': 'web推流',
                                }, (code, msg, info) => {
                                    if (code === 0) {
                                        this.stream = info[0].stream
                                        Http.request(Http.changeXqLive, {
                                            'uid': this.uid,
                                            'token': this.token,
                                            'stream': this.stream,
                                            'status': '1',
                                        })
                                    }
                                })


                            })
                        })
                    }
                })

            },

            /**
             * 初始化Rtc 并加入通道
             */
            initAndJoin(onJoinSucc) {
                console.log("Agora:", "初始化rtcClient")
                let rtcClient = AgoraRTC.createClient({mode: "live", codec: "h264"})
                this.rtcClient = rtcClient
                //注册事件

                //该回调通知远端用户发布了新的音频轨道或者视频轨道。
                //你可以在该回调中订阅并播放远端用户的音视频轨道
                //如果用户加入频道时频道内已经有其他用户的音视频轨道，也会收到该回调报告已经存在的远端轨道。
                rtcClient.on("user-published", (rtcUser, mediaType) => {
                    console.log("Agora: user-published--rtcUser->", rtcUser.uid)
                    console.log("Agora: user-published--mediaType->", mediaType)

                    this.rtcClient.subscribe(rtcUser, mediaType).then(res => {
                        console.log("Agora: user-published--subscribe->", res)

                        let uid = rtcUser.uid.toString()
                        if (uid === this.anchorInfo.uid) {//收到主播的推拉流信息
                            if (mediaType === "video") {
                                let videoTrack = rtcUser.videoTrack
                                this.anchorInfo.videoTrack = videoTrack
                                videoTrack.play(this.$refs.anchorView)
                            } else if (mediaType === "audio") {
                                let audioTrack = rtcUser.audioTrack
                                this.anchorInfo.audioTrack = audioTrack
                                audioTrack.play()
                            }


                        } else {//收到其他观众的推拉流信息
                            let index = this.audienceInfo.findIndex(value => value.uid === uid)
                            let joinUser = undefined
                            if (index < 0) {
                                joinUser = {uid}
                                this.audienceInfo.push(joinUser)
                            } else {
                                joinUser = this.audienceInfo[index]
                            }
                            if (mediaType === "video") {
                                joinUser.videoTrack = rtcUser.videoTrack

                                const remotePlayerContainer = document.createElement("div");
                                remotePlayerContainer.id = uid;
                                remotePlayerContainer.style.width = '140px'
                                remotePlayerContainer.style.height = '200px'
                                remotePlayerContainer.style.border = '#000 1px solid'
                                remotePlayerContainer.style.backgroundColor = '#ccc'
                                remotePlayerContainer.style.boxSizing = 'border-box'
                                this.$refs.audienceView.append(remotePlayerContainer);
                                joinUser.videoTrack.play(remotePlayerContainer)
                            } else if (mediaType === "audio") {
                                joinUser.audioTrack = rtcUser.audioTrack
                                joinUser.audioTrack.play()
                            }
                        }


                    })
                })


                //用户取消推流
                rtcClient.on("user-unpublished", user => {
                    const remotePlayerContainer = document.getElementById(user.uid);
                    remotePlayerContainer.remove();
                });

                console.log('agoraAppId:', appConfig.agoraAppId)

                //加入通道
                rtcClient.join(appConfig.agoraAppId, this.uid, this.rtcToken, parseInt(this.uid))
                    .then(res => {
                        console.log("Agora:", "加入通道成功")
                        if (onJoinSucc) {
                            onJoinSucc()
                        }
                    })
                    .catch(error => {
                        console.log("Agora:", "加入通道失败：", error)
                        Toast.show("加入通道失败：" + error.message)
                    })
            },

            /**
             * 开始推流
             */
            startPush(callback) {
                this.rtcClient.setClientRole("host");
                Promise.all([
                    AgoraRTC.createMicrophoneAudioTrack({
                        encoderConfig: {
                            sampleRate: 48000,
                            stereo: true,
                            bitrate: 128,
                        },
                    }),
                    AgoraRTC.createCameraVideoTrack({
                        encoderConfig: {
                            width: 640,
                            // 支持指定一个范围和参考值，具体配置参考相关 API 文档
                            height: {ideal: 480, min: 400, max: 500},
                            frameRate: 15,
                            bitrateMin: 600, bitrateMax: 1000,
                        },
                    })
                ]).then(audioAndVideoTrack => {//用来推流的 音频和视频轨道的数组[0]音频 [1]视频
                    console.log("Agora:", "创建音频和视频轨道:", audioAndVideoTrack)
                    this.rtcClient.publish(audioAndVideoTrack).then(() => {
                        console.log("Agora:", "推流成功")
                        if (callback) {
                            callback(audioAndVideoTrack)
                        }
                    })
                })
            },

            /**
             * 离开房间
             */
            leaveRoom() {
                let array = []
                if (this.uid === this.anchorInfo.uid) {//自己是主播
                    //取消自己的推流
                    array.push(this.rtcClient.unpublish())
                    this.audienceInfo.forEach(value => {
                        //取消订阅其他观众的流
                        this.rtcClient.unsubscribe(parseInt(value.id))
                    })
                } else {
                    //取消主播的推流
                    array.push(this.rtcClient.unsubscribe(parseInt(this.anchorInfo.uid)))
                    this.audienceInfo.forEach(value => {
                        if (this.uid === value.uid) {
                            //取消自己的推流
                            array.push(this.rtcClient.unpublish())
                        } else {
                            //取消订阅其他观众的流
                            this.rtcClient.unsubscribe(parseInt(value.id))
                        }
                    })
                }
                Promise.all(array).finally(() => {
                    console.log("Agora:", "取消所有的推流和播流")
                    if (this.uid === this.anchorInfo.uid) {
                        if (this.anchorInfo.audioTrack) {
                            console.log("Agora:", "主播关闭音频轨道")
                            this.anchorInfo.audioTrack.close()
                        }
                        if (this.anchorInfo.videoTrack) {
                            console.log("Agora:", "主播关闭视频轨道")
                            this.anchorInfo.videoTrack.close()
                        }
                    } else {
                        //自己是否在推流
                        let selfMicInfo = this.audienceInfo.find(value => value.uid === this.uid)
                        if (selfMicInfo) {
                            if (selfMicInfo.audioTrack) {
                                console.log("Agora:", "自己关闭音频轨道")
                                selfMicInfo.audioTrack.close()
                            }
                            if (selfMicInfo.videoTrack) {
                                console.log("Agora:", "自己关闭视频轨道")
                                selfMicInfo.videoTrack.close()
                            }
                        }
                    }

                    this.rtcClient.leave().then(res => {
                        console.log("Agora:", "离开通道：", res)
                    })

                })
            },
        },
        mounted() {
            this.getXqRoomList()
        },
        beforeDestroy() {
            this.leaveRoom()
        }
    }
</script>

<style scoped>
</style>
